package com.guang.executor.executorpool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lg
 * @Description  证明核心线程被销毁了
 *              需要将超时时间单位设置的小一点，然后让非核心线程开始来进行工作！看一下非核心线程是否还存在
 * @date 2022/10/24 17:39
 */
public class ExecutorPoolTestDestroy {
    private static Logger logger = LoggerFactory.getLogger(ExecutorPoolTestDestroy.class);
    private static int CORE_THREAD_COUNT = Runtime.getRuntime().availableProcessors()+1;
    private static final String FIX_THREAD_NAME = "FixThreadPool_";
    // 不需要临时线程了，因为LinkedBlockingDeque默认长度是2的三十一次方-1
    private static final ThreadPoolExecutor EXECUTOR_SERVICE = new ThreadPoolExecutor(1,
            2,
            5, TimeUnit.MICROSECONDS,
            new ArrayBlockingQueue(1),
            new ThreadFactory() {
                    AtomicInteger atomicInteger = new AtomicInteger(1);
                    // 自定义生产线程的工厂
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r,FIX_THREAD_NAME+atomicInteger.getAndIncrement());
                }
            },new ThreadPoolExecutor.AbortPolicy()
    );

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            EXECUTOR_SERVICE.execute(new MyTask());
        }
        TimeUnit.SECONDS.sleep(2);
        logger.info("执行三个任务。核心队列执行一个，队列中放一个，剩下一个将会交给非核心线程来执行");
        TimeUnit.SECONDS.sleep(2);
        logger.info("当前线程池中的数量为:{}",EXECUTOR_SERVICE.getPoolSize()); // 1
    }

    private static class MyTask implements Runnable{
        @Override
        public void run() {
            logger.info("在执行线程任务的时候打印当前线程名称:{}",Thread.currentThread().getName());
            // logger.info("start..........");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // logger.info("end..........");
        }
    }
}
